package com.example.demo.controller;

import com.example.demo.bean.Result;
import com.example.demo.biz.AdminBiz;
import com.example.demo.pojo.Adminuser;
import com.example.demo.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.validation.Valid;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/5/23.
 */
@RestController
public class AdminController {

    private final static Logger logger = LoggerFactory.getLogger(AdminController.class);

    @Autowired
    private AdminBiz adminBiz;

    @PostMapping("admin")
    public Result<Adminuser> add(@Valid Adminuser admin, BindingResult result) throws Exception {
        logger.info("增加对象");

        if (result.hasErrors()) {
            return ResultUtil.error(2, result.getFieldError().getDefaultMessage());
        }
        Adminuser adminuser = adminBiz.add(admin);
        if (adminuser != null) {
            return ResultUtil.success(adminuser);
        } else {
            return ResultUtil.error(2, "增加失败");
        }

    }

    @GetMapping("admin")
    public Result<List<Adminuser>> list() {
        logger.info("查询所有");
        List<Adminuser> list = adminBiz.list();
        return ResultUtil.success(list);
    }
    @GetMapping("findByid")
    public Result<Adminuser> findByid(Integer id) throws Exception {
        logger.info("通过ID查询对象");
        Adminuser admin = adminBiz.findById(id);
        return ResultUtil.success(admin);
    }


    /**
     * 登陆
     */
    /**
     * 用户和Session绑定关系
     */
    public static final Map<String, HttpSession> USER_SESSION=new HashMap<String, HttpSession>();

    /**
     * seeionId和用户的绑定关系
     */
    public static final Map<String, String> SESSIONID_USER=new HashMap<String, String>();

    public void sessionDestroyed(HttpSessionEvent se) {
        String sessionId=se.getSession().getId();
        //当前session销毁时删除当前session绑定的用户信息
        //同时删除当前session绑定用户的HttpSession
        USER_SESSION.remove(SESSIONID_USER.remove(sessionId));
    }
    /**
     * 用户登录时的处理
     * 处理一个账号同时只有一个地方登录的关键
     * @param request
     */
    public static boolean userLoginHandle(HttpServletRequest request){
        //当前登录的用户
        String userName=request.getParameter("aname");
        //当前sessionId
        String sessionId=request.getSession().getId();
        //删除当前sessionId绑定的用户，用户--HttpSession
        USER_SESSION.remove(SESSIONID_USER.remove(sessionId));

        //删除当前登录用户绑定的HttpSession
        HttpSession session=USER_SESSION.remove(userName);
        if(session!=null){
            SESSIONID_USER.remove(session.getId());
            session.removeAttribute("aname");
            session.setAttribute("userMsg", "您的账号已经在另一处登录了,你被迫下线!");
            return true;
        }
        return false;
    }

    /**
     * 用户登录
     */
    @RequestMapping("service")
    public Result service(HttpServletRequest request,Adminuser adminuser) throws ServletException, IOException {
        logger.info("登陆");
        if(adminuser.getAname()!=null&&!"".equals(adminuser.getAname().trim())){
            //登录成功
            Adminuser login = adminBiz.login(adminuser);
            if(login!=null){
                HttpSession session=request.getSession();
                //处理用户登录(保持同一时间同一账号只能在一处登录)
                boolean b = userLoginHandle(request);
                if (b){
                    return ResultUtil.error(1,"您的账号已经在另一处登录了,你被迫下线!");
                }
                //添加用户与HttpSession的绑定
                USER_SESSION.put(adminuser.getAname().trim(), session);
                //添加sessionId和用户的绑定
                SESSIONID_USER.put(session.getId(), adminuser.getAname());

                session.setAttribute("aname", adminuser.getAname());
                session.removeAttribute("userMsg");
                return ResultUtil.success(login);
            }
        }
        return ResultUtil.error(2,"登陆失败");
    }


}
